/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatspace.converters;

import java.util.Date;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 *
 * @author ghanemel
 */
public class RelativeDateTimeConverter implements Converter {

    private static final String[] periods = {"second", "minute", "hour", "day", "week", "month", "year", "decade"};
    private static final double[] lengths = {60, 60, 24, 7, 4.35, 12, 10};


    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {

        Date now = new Date();
        Date date = (Date) value;
        long diff = (now.getTime() - date.getTime()) / 1000; // diff in seconds

        int j = 0;
        for (int i = 0; diff >= lengths[i] && i < lengths.length - 1; i++) {
            j = i;
            diff = (long) (diff / lengths[i]);
        }

        String period = periods[j + 1];
        if (diff != 1) {
            period = period + "s";
        }
        return diff + " " + period + " ago";
    }

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
        return null;
    }
}